import { createSlice } from '@reduxjs/toolkit'
import request from '../../utils/request'
import {
  getLocalChannels,
  hasToken,
  setLocalChannels,
} from '../../utils/storage'

const home = createSlice({
  name: 'home',
  initialState: {
    channels: [],
    //存储所有文章列表
    articleList: {},
  },
  reducers: {
    saveChannels: (state, action) => {
      state.channels = action.payload
    },
    setArticleList: (state, action) => {
      state.articleList = {
        ...state.articleList,
        [action.payload.channelId]: {
          timestamp: action.payload.timestamp,
          list: action.payload.list,
        },
      }
    },
    setMoreArticleList: (state, action) => {
      //如果loadMore为true，代码加载更多数据，不应该覆盖，应该追加
      state.articleList = {
        ...state.articleList,
        [action.payload.channelId]: {
          timestamp: action.payload.timestamp,
          list: [
            ...state.articleList[action.payload.channelId].list,
            ...action.payload.list,
          ],
        },
      }
    },
  },
})

export const { saveChannels, setArticleList, setMoreArticleList } = home.actions

export const getUserChannels = () => {
  return async (dispatch) => {
    //判断用户是否登录
    if (hasToken()) {
      const res = await request.get('user/channels')
      // console.log(res.data)
      dispatch(saveChannels(res.data.channels))
    } else {
      //没有token，从本地去获取数据
      const localChannels = getLocalChannels()
      if (localChannels) {
        // 没有token，但本地有channels
        dispatch(saveChannels(localChannels))
      } else {
        //没有token，本地也没有channels
        const res = await request.get('user/channels')
        // console.log(res.data)
        dispatch(saveChannels(res.data.channels))
        setLocalChannels(res.data.channels)
      }
    }
  }
}

//获取文章列表
export const getArticleList = (channelId, timestamp, loadMore = false) => {
  return async (dispatch) => {
    const res = await request({
      url: 'articles',
      method: 'get',
      params: {
        channel_id: channelId,
        timestamp: timestamp,
      },
    })
    // console.log(res)
    if (loadMore) {
      // console.log(1)
      dispatch(
        setMoreArticleList({
          channelId,
          timestamp: res.data.pre_timestamp,
          list: res.data.results,
        })
      )
    } else {
      // console.log(2)
      dispatch(
        setArticleList({
          channelId,
          timestamp: res.data.pre_timestamp,
          list: res.data.results,
        })
      )
    }
  }
}

export default home.reducer
